package client.comm.commlib.base

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.paging.LoadState
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil

abstract class BasePagingAdapter<T : Any>(differCallback: DiffUtil.ItemCallback<T>) :
    PagingDataAdapter<T, PagingViewHoder>(differCallback) {

    var refreshLoading: (() -> Unit)? = null
    var refreshNotLoading: (() -> Unit)? = null
    var refreshError: ((e: LoadState.Error) -> Unit)? = null

    var appendError: ((e: LoadState.Error) -> Unit)? = null

    init {
        addLoadStateListener {
            when (it.refresh) {
                is LoadState.NotLoading -> {
                    refreshNotLoading?.invoke()
                }

                is LoadState.Loading -> {
                    refreshLoading?.invoke()
                }

                is LoadState.Error -> {
                    refreshError?.invoke(it.refresh as LoadState.Error)
                }
            }
            when (it.append) {
                is LoadState.Error -> {
                    appendError?.invoke(it.append as LoadState.Error)
                }
                else -> {}
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PagingViewHoder {
        return PagingViewHoder(
            DataBindingUtil.inflate(
                LayoutInflater.from(parent.context),
                getItemLayout(),
                parent,
                false
            )
        )
    }

    override fun onBindViewHolder(holder: PagingViewHoder, position: Int) {
        bindItem(holder, getItem(position) as Any)
    }

    abstract fun bindItem(holder: PagingViewHoder, t: Any)
    abstract fun getItemLayout(): Int
}